package com.pet.shop.service.user;

import com.github.pagehelper.Page;
import com.pet.config.Constants;
import com.pet.exceptions.BusinessException;
import com.pet.shop.dto.PageDto;
import com.pet.shop.entity.user.SysUser;
import com.pet.shop.mappers.user.SysUserMapper;
import com.pet.shop.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class SysUserServiceImpl implements ISysUserService{

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public int deleteEntity(Long id) {
        return sysUserMapper.delete(id);
    }

    @Override
    public int deleteEntityList(List<Long> idList) {
        int i = 0;
        for(Long id : idList){
            i += sysUserMapper.delete(id);
        }
        return i;
    }

    @Override
    public SysUser insertEntity(SysUser record) {
        if(StringUtils.isEmpty(record.getLoginName())){
            throw new BusinessException("登录账号不能为空");
        }
        if(StringUtils.isEmpty(record.getPassword())){
            throw new BusinessException("登录密码不能为空");
        }
        SysUser serverUser = sysUserMapper.queryByLoginName(record.getLoginName());
        if(serverUser != null){
            throw new BusinessException("登录账号不能重复");
        }
        record.setPassword(MD5Util.md5(record.getPassword()));
        if(record.getIsLogin() == null){
            record.setIsLogin(Constants.IS_LOGIN_NO);
        }
        sysUserMapper.insert(record);
        return record;
    }

    @Override
    public SysUser getEntity(Long id) {
        return sysUserMapper.get(id);
    }

    @Override
    public int updateEntity(SysUser record) {
        return sysUserMapper.update(record);
    }

    @Override
    public PageDto<SysUser> queryPage(PageDto<SysUser> pageDto) {
        Page<SysUser> page =  sysUserMapper.queryPage(pageDto);
        if(page.getResult() != null) page.getResult().forEach(sysUser -> sysUser.setPassword(null));
        pageDto.setPageResult(page);
        return pageDto;
    }

    @Override
    public SysUser queryByLoginName(String loginName) {
        return sysUserMapper.queryByLoginName(loginName);
    }
}
